package com.example.wifidirect

import android.annotation.SuppressLint
import android.app.Service
import android.content.Context
import android.content.Intent
import android.net.wifi.p2p.WifiP2pManager
import android.net.wifi.p2p.nsd.WifiP2pDnsSdServiceRequest
import android.os.IBinder
import android.util.Log

class WifiDirectService : Service() {
    private lateinit var manager: WifiP2pManager
    private lateinit var channel: WifiP2pManager.Channel

    override fun onBind(intent: Intent): IBinder {
        TODO("Return the communication channel to the service.")
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        manager = getSystemService(Context.WIFI_P2P_SERVICE) as WifiP2pManager
        // Registers the application with the Wi-Fi framework.
        channel = manager.initialize(this, mainLooper) {
            Log.d("onChannelDisconnected", "The channel to the framework has been disconnected.")
        }

        startServiceDiscovery()
        return START_STICKY
    }

    private fun startServiceDiscovery() {
        val serviceRequest = WifiP2pDnsSdServiceRequest.newInstance()
        manager.addServiceRequest(channel, serviceRequest, object : WifiP2pManager.ActionListener {
            @SuppressLint("MissingPermission")
            override fun onSuccess() {
                manager.discoverServices(channel, object : WifiP2pManager.ActionListener {
                    override fun onSuccess() {
                        Log.d("WifiP2PService", "Service discovery started successfully")
                    }

                    override fun onFailure(reason: Int) {
                        Log.e("WifiP2PService", "Service discovery failed: $reason")
                    }
                })
            }

            override fun onFailure(reason: Int) {
                Log.e("WifiP2PService", "Add service request failed: $reason")
            }
        })
    }

    private val buddies = mutableMapOf<String, String>()

    private fun addDiscoverServiceRequest() {
        /* Callback includes:
         * fullDomain: full domain name: e.g. "printer._ipp._tcp.local."
         * record: TXT record dta as a map of key/value pairs.
         * device: The device running the advertised service.
         */
        val txtListener = WifiP2pManager.DnsSdTxtRecordListener { fullDomainName, txtRecordMap, srcDevice ->
            Log.d("DnsSdTxtRecord", "DnsSdTxtRecord available - $fullDomainName, $txtRecordMap, $srcDevice")
            txtRecordMap["buddyname"]?.also {
                buddies[srcDevice.deviceAddress] = it
            }
        }

        val servListener =
            WifiP2pManager.DnsSdServiceResponseListener { instanceName, registrationType, srcDevice ->
                // Update the device name with the human-friendly version from
                // the DnsTxtRecord, assuming one arrived.
                srcDevice.deviceName =
                    buddies[srcDevice.deviceAddress] ?: srcDevice.deviceName

                Log.d("DnsSdService", "发现服务实例: $instanceName, 类型: $registrationType, 设备: ${srcDevice.deviceName}")

            }

        manager.setDnsSdResponseListeners(channel, servListener, txtListener)

        val serviceRequest = WifiP2pDnsSdServiceRequest.newInstance()
        manager.addServiceRequest(
            channel,
            serviceRequest,
            object : WifiP2pManager.ActionListener {
                override fun onSuccess() {
                    // Success!
                }

                override fun onFailure(code: Int) {
                    // Command failed.  Check for P2P_UNSUPPORTED, ERROR, or BUSY
                }
            }
        )


    }

}